// 云函数 - 创建订单（支持规格价格偏移和微信支付）
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { addressId, totalAmount, actualAmount, discountAmount, items, paymentMethods, notes, paymentPassword } = event

  try {
    // 验证用户登录状态
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }

    // 验证订单数据
    if (!addressId || !items || items.length === 0) {
      return {
        success: false,
        message: '订单数据不完整'
      }
    }

    // 重新计算订单金额，确保价格正确
    let calculatedTotal = 0
    const processedItems = []

    for (const item of items) {
      // 验证商品信息
      const goodsResult = await db.collection('goods').doc(item.productId).get()
      if (!goodsResult.data) {
        return {
          success: false,
          message: `商品 ${item.name} 不存在`
        }
      }

      const goodsData = goodsResult.data
      
      // 计算规格价格偏移
      let specOffset = 0
      if (item.selectedSpec && goodsData.specifications) {
        goodsData.specifications.forEach(spec => {
          if (spec.offset && Array.isArray(spec.offset) && item.selectedSpec[spec.name]) {
            const selectedOptionName = item.selectedSpec[spec.name].name || item.selectedSpec[spec.name]
            const optionIndex = spec.options.findIndex(option => 
              (typeof option === 'string' ? option : option.name) === selectedOptionName
            )
            
            if (optionIndex !== -1 && optionIndex < spec.offset.length && typeof spec.offset[optionIndex] === 'number') {
              specOffset += spec.offset[optionIndex]
            }
          }
        })
      }

      // 计算最终价格
      const basePrice = parseFloat(goodsData.price) || 0
      const finalPrice = basePrice + specOffset
      const itemTotal = finalPrice * item.quantity

      calculatedTotal += itemTotal

      // 检查库存
      if (goodsData.stock < item.quantity) {
        return {
          success: false,
          message: `商品 ${item.name} 库存不足`
        }
      }

      processedItems.push({
        productId: item.productId,
        name: item.name,
        basePrice: parseFloat(basePrice.toFixed(2)),
        specOffset: parseFloat(specOffset.toFixed(2)),
        finalPrice: parseFloat(finalPrice.toFixed(2)),
        quantity: item.quantity,
        subtotal: parseFloat(itemTotal.toFixed(2)),
        image: item.image,
        specifications: item.specifications,
        selectedSpec: item.selectedSpec
      })
    }

    // 验证计算的金额是否匹配
    const calculatedTotalFixed = parseFloat(calculatedTotal.toFixed(2))
    const totalAmountFixed = parseFloat(totalAmount.toFixed(2))
    if (calculatedTotalFixed !== totalAmountFixed) {
      return {
        success: false,
        message: `订单金额计算错误: 计算值${calculatedTotalFixed}, 传入值${totalAmountFixed}`
      }
    }

    // 直接使用openid作为用户标识
    const userOpenid = wxContext.OPENID

    // 验证地址信息
    const addressResult = await db.collection('addresses')
      .where({
        userId: userOpenid,
        _id: addressId
      })
      .get()

    if (addressResult.data.length === 0) {
      return {
        success: false,
        message: '收货地址不存在'
      }
    }

    // 分析支付方式
    const balancePayment = paymentMethods.find(method => method.id === 'balance')
    const wechatPayment = paymentMethods.find(method => method.id === 'wechat')
    const comboPayment = paymentMethods.find(method => method.id === 'combo')
    
    // 获取用户余额信息（用于验证）
    const userResult = await db.collection('users').where({
      _openid: userOpenid
    }).get()
    const userBalance = parseFloat((userResult.data[0]?.balance || 0).toFixed(2))
    
    // 验证余额支付
    if (balancePayment && balancePayment.amount > 0) {
      if (userBalance < balancePayment.amount) {
        return {
          success: false,
          message: '余额不足'
        }
      }
      
      // 验证支付密码
      if (!paymentPassword) {
        return {
          success: false,
          message: '请输入支付密码',
          needPassword: true
        }
      }
      
      // 检查用户是否设置了支付密码
      const userPaymentPassword = userResult.data[0]?.paymentPassword
      if (!userPaymentPassword) {
        return {
          success: false,
          message: '请先设置支付密码',
          needSetPassword: true
        }
      }
      
      // 验证支付密码
      const crypto = require('crypto')
      const hashedPassword = crypto.createHash('sha256').update(paymentPassword).digest('hex')
      if (userPaymentPassword !== hashedPassword) {
        // 记录错误次数
        const errorCount = (userResult.data[0].passwordErrorCount || 0) + 1
        await db.collection('users').where({
          _openid: userOpenid
        }).update({
          data: {
            passwordErrorCount: errorCount,
            lastPasswordErrorTime: new Date(),
            updateTime: new Date()
          }
        })
        
        // 如果错误次数过多，实施临时锁定
        if (errorCount >= 5) {
          return {
            success: false,
            message: '密码错误次数过多，请稍后再试',
            locked: true
          }
        }
        
        return {
          success: false,
          message: '支付密码错误'
        }
      }
      
      // 密码正确，清除错误计数
      await db.collection('users').where({
        _openid: userOpenid
      }).update({
        data: {
          passwordErrorCount: 0,
          lastPasswordErrorTime: null,
          updateTime: new Date()
        }
      })
    }
    
    
    // 验证组合支付
    if (comboPayment && comboPayment.amount > 0) {
      const balanceAmount = parseFloat((comboPayment.balanceAmount || 0).toFixed(2))
      const wechatAmount = parseFloat((comboPayment.wechatAmount || 0).toFixed(2))
      
      if (userBalance < balanceAmount) {
        return {
          success: false,
          message: '余额不足，无法使用组合支付'
        }
      }
      
      const totalPaymentAmount = parseFloat((balanceAmount + wechatAmount).toFixed(2))
      const actualAmountFixed = parseFloat(actualAmount.toFixed(2))
      if (totalPaymentAmount !== actualAmountFixed) {
        return {
          success: false,
          message: '组合支付金额不匹配'
        }
      }
      
      // 组合支付中包含余额支付，需要验证支付密码
      if (balanceAmount > 0) {
        if (!paymentPassword) {
          return {
            success: false,
            message: '请输入支付密码',
            needPassword: true
          }
        }
        
        // 检查用户是否设置了支付密码
        const userPaymentPassword = userResult.data[0]?.paymentPassword
        if (!userPaymentPassword) {
          return {
            success: false,
            message: '请先设置支付密码',
            needSetPassword: true
          }
        }
        
        // 验证支付密码
        const crypto = require('crypto')
        const hashedPassword = crypto.createHash('sha256').update(paymentPassword).digest('hex')
        if (userPaymentPassword !== hashedPassword) {
          // 记录错误次数
          const errorCount = (userResult.data[0].passwordErrorCount || 0) + 1
          await db.collection('users').where({
            _openid: userOpenid
          }).update({
            data: {
              passwordErrorCount: errorCount,
              lastPasswordErrorTime: new Date(),
              updateTime: new Date()
            }
          })
          
          // 如果错误次数过多，实施临时锁定
          if (errorCount >= 5) {
            return {
              success: false,
              message: '密码错误次数过多，请稍后再试',
              locked: true
            }
          }
          
          return {
            success: false,
            message: '支付密码错误'
          }
        }
        
        // 密码正确，清除错误计数
        await db.collection('users').where({
          _openid: userOpenid
        }).update({
          data: {
            passwordErrorCount: 0,
            lastPasswordErrorTime: null,
            updateTime: new Date()
          }
        })
      }
    }

    // 生成订单号
    const orderNo = 'ORD' + Date.now() + Math.random().toString(36).substr(2, 6).toUpperCase()

    // 确定初始订单状态
    let initialStatus = 'pending_payment' // 默认待付款
    if (balancePayment && balancePayment.amount === actualAmount) {
      // 纯余额支付，直接设为已支付
      initialStatus = 'paid'
    }
    // 组合支付和微信支付都需要等待微信支付完成

    // 创建订单
    const orderData = {
      userId: userOpenid,
      orderNo: orderNo,
      status: initialStatus,
      addressId: addressId,
      address: addressResult.data[0],
      items: processedItems,
      totalAmount: parseFloat(totalAmount.toFixed(2)),
      discountAmount: parseFloat((discountAmount || 0).toFixed(2)),
      actualAmount: parseFloat(actualAmount.toFixed(2)),
      paymentMethods: paymentMethods,
      notes: notes || '',
      createTime: new Date(),
      updateTime: new Date()
    }

    const orderResult = await db.collection('orders').add({
      data: orderData
    })

    // 处理余额支付
    if (balancePayment && balancePayment.amount > 0) {
      // 扣除用户余额并增加总消费额
      const balanceAmount = parseFloat(balancePayment.amount.toFixed(2))
      await db.collection('users').where({
        _openid: userOpenid
      }).update({
        data: {
          balance: db.command.inc(-balanceAmount),
          totalConsumption: db.command.inc(balanceAmount),
          updateTime: new Date()
        }
      })

      // 如果是纯余额支付，更新订单状态并减少库存
      if (balanceAmount === parseFloat(actualAmount.toFixed(2))) {
        await db.collection('orders').doc(orderResult._id).update({
          data: {
            status: 'pending_shipment', // 待发货
            payTime: new Date(),
            updateTime: new Date()
          }
        })

        // 减少商品库存
        for (const item of processedItems) {
          await db.collection('goods').doc(item.productId).update({
            data: {
              stock: db.command.inc(-item.quantity),
              sales: db.command.inc(item.quantity),
              updateTime: new Date()
            }
          })
        }
      }
    }

    // 处理微信支付（包括纯微信支付和组合支付）
    const needWechatPay = (wechatPayment && wechatPayment.amount > 0) || 
                         (comboPayment && comboPayment.wechatAmount > 0)
    if (needWechatPay) {
      // 确定微信支付金额
      const wechatAmount = parseFloat((wechatPayment ? wechatPayment.amount : comboPayment.wechatAmount).toFixed(2))
      const paymentType = comboPayment ? 'combo' : 'wechat'
      try {
        // 获取当前环境 ID
        const envId = process.env.TCB_ENV
        console.log("当前环境 ID:", envId)
        
        // 调用微信支付统一下单
        const payResult = await cloud.cloudPay.unifiedOrder({
          body: `圣义文化商城-订单${orderNo}`,
          outTradeNo: orderNo,
          totalFee: Math.round(wechatAmount * 100), // 转换为分
          envId: envId, // 使用环境变量获取的环境ID
          subMchId: '1724228888', // 子商户号，需要根据实际情况配置
          tradeType: 'JSAPI',
          openid: userOpenid, // 用户openid
          spbillCreateIp: wxContext.CLIENTIP || '127.0.0.1', // 客户端IP
          functionName: 'payNotify', // 支付回调云函数名
          attach: JSON.stringify({
            o: orderNo,
            t: paymentType === 'combo' ? 'c' : (paymentType === 'wechat' ? 'w' : 'b'),
            b: comboPayment ? comboPayment.balanceAmount || 0 : 0
          })
        })

        console.log('云开发支付下单结果:', payResult)

        if (payResult.returnCode === 'SUCCESS' && payResult.resultCode === 'SUCCESS') {
          // 直接返回云开发的支付参数，符合标准做法
          return {
            ...payResult,
            // 附加业务信息供前端使用
            success: true,
            message: '订单创建成功',
            orderId: orderResult._id,
            orderNo: orderNo,
            paymentType: paymentType
          }
        } else {
          console.error('微信支付下单失败:', payResult)
          // 微信支付下单失败，删除已创建的订单
          await db.collection('orders').doc(orderResult._id).remove()
          return {
            success: false,
            message: '创建支付订单失败: ' + (payResult.errMsg || payResult.returnMsg || '微信支付下单失败，请重试')
          }
        }
      } catch (payError) {
        console.error('微信支付API调用失败:', payError)
        // 删除已创建的订单
        await db.collection('orders').doc(orderResult._id).remove()
        return {
          success: false,
          message: '支付服务异常，请稍后重试'
        }
      }
    }

    return {
      success: true,
      message: '订单创建成功',
      orderId: orderResult._id,
      orderNo: orderNo,
      paymentType: 'balance'
    }

  } catch (error) {
    console.error('创建订单失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    return {
      success: false,
      message: `创建订单失败: ${error.message || '请重试'}`
    }
  }
}